const express = require("express");
const handleDB = require("../db/handleDB");
const common = require("../utils/common");
const keys = require('../keys');
const md5 = require("md5");
const multer = require('multer');
const upload_file = require("../utils/qn");
const upload = multer({ dest:'public/news/upload/avater' })
const constant = require('../utils/constant')
const router = express.Router();
router.get('/profile',(req,res)=>{
    (async function(){
        let userInfo = await common.getUserInfo(req,res);
        
        let data = {
            user_info:{
                nick_name: userInfo[0].nick_name,
                avatar_url: userInfo[0].avatar_url?(constant.QINIU_AVATAR_URL_PRE + userInfo[0].avatar_url):"/news/images/worm.jpg"
            }
        }
        res.render('news/user',data)
    })()
})
router.all('/user/base_info',(req,res)=>{
    (async function(){
        let userInfo = await common.getUser(req,res);
        if(req.method==='GET'){
            let data = {
                nick_name:userInfo[0].nick_name,
                signature:userInfo[0].signature,
                gender:userInfo[0].gender?userInfo[0].gender:'MAN'
            }
            res.render('news/user_base_info',data);
        }else if(req.method==="POST"){
            /*
            
                1、获取参数判空
                2、修改数据库中的用户数据
                3、返回操作成功
            */

        //    1、获取参数判空
            let {signature, nick_name, gender} = req.body
            if(!signature || !nick_name || !gender){
                res.send({errmsg:"参数错误"})
                return
            }
        //    2、修改数据库中的用户数据
            await handleDB(res, "info_user", "update", "数据库更新数据出错", `id=${userInfo[0].id}`,{
                signature,
                nick_name,
                gender
            })
        //    3、返回操作成功
            res.send({errno:"0", errmsg:"操作成功"})
        }
    })();
})
router.all('/user/pass_info',(req,res)=>{
    (async function(){
        let userInfo = await common.getUser(req,res);
        if(req.method==='GET'){
            res.render('news/user_pass_info')
        }else if(req.method==='POST'){
            const {old_password,new_password,new_password2} = req.body;
            if(!old_password || !new_password || !new_password2){
                res.send({errmsg:'参数错误'})
                return
            }
            if(new_password !== new_password2){
                res.send({errmsg:'两次密码不一致'})
                return
            }
            if(md5(md5(old_password)+keys.password_salt)!==userInfo[0].password_hash){
                res.send({errmsg:'旧密码不正确，修改失败'})
                return
            }
            await handleDB(res,'info_user','update','数据库更新数据出错',`id=${userInfo[0].id}`,{
                password_hash:md5(md5(new_password)+keys.password_salt)
            })
            res.send({errno:'0',errmsg:'操作成功'})
        }
    })();
})
router.get('/user/pic_info',(req,res)=>{
    (async function(){
        const userInfo = await common.getUserInfo(req,res);
        res.render('news/user_pic_info')
    })()
    res.render('news/user_pic_info')
})
router.post('/user/pic_info',upload.single('avatar'),(req,res)=>{
    (async function(){
        const userInfo = await common.getUserInfo(req,res);
        /*
        req.file为以下对象
        {
            fieldname: 'avatar',
            originalname: '01.jpg',
            encoding: '7bit',
            mimetype: 'image/jpeg',
            destination: 'public/news/upload/avater',
            filename: '075adb9e3f1afa00bfcccc4090dcd12f',
            path: 'public\\news\\upload\\avater\\075adb9e3f1afa00bfcccc4090dcd12f',
            size: 410141
        }
        */
        // uploac_file(上传后的名字，上传的图片路径) 上传的图片相对路径，从项目文件夹出发
        
        // 1、接收上传图片的对象req.file
        const file = req.file
        // 2、上传图片到七牛云服务器
        try{
            const retObj = await upload_file(file.originalname,`${file.destination}/${file.filename}`)
        }catch(error){
            res.send({errmsg:'上传七牛云失败'})
            return
        }
        // 3、把七牛云返回的对象的key属性保存到数据库
        await handleDB(res,'info_user','update','数据库修改数据失败',`id=${userInfo[0].id}`,{
            avatar_url:file.originalname
        })
        // 4、返回上传成功
        const data = {
            avatar_url:constant.QINIU_AVATAR_URL_PRE + file.originalname
        }
        res.send({errno:'0',errmsg:'上传成功',data})
    })()
})
// 展示收藏的新闻的页面
router.get("/user/collections",(req, res)=>{
    (async function(){
        let userInfo = await common.getUserInfo(req, res);

        let {p=1} = req.query

        let currentPage = p;
        //总页数 = 总条数/每页多少条   向上取整
        // 总条数  counts   登录用户收藏了多少条新闻，查收藏表 info_user_collection
        let counts = await handleDB(res, "info_user_collection", "sql", "数据库查询出错", 
            `select count(*) from info_user_collection where user_id=${userInfo[0].id}`
        )  //  [{"count(*)": 50}]

        

        // 最终要查询的表示info_news表(标题和创建时间字段),   要查询的是登录的用户收藏过的新闻 
        //  1、先查询到登录用户收藏过的新闻的id(分页查询出来)  limit (第几页的数据-1)*每页多少条,每页多少条
        let collectionNewsIdList = await handleDB(res, "info_user_collection", "find", "数据库查询错误2", `user_id=${userInfo[0].id} limit ${(currentPage-1)*10},10`);
        console.log(collectionNewsIdList);   // id数组

        let collectionNewsList = []
        // 遍历这个id数组，拿着里面每一个元素的news_id属性去查询info_news表
        // 把查询的每一个结果push到collectionNewsList
        for(var i = 0;i<collectionNewsIdList.length;i++){
            // collectionNewsIdList[i] 表示id数组的每一个元素   collectionNewsIdList[i].news_id
            let ret = await handleDB(res, "info_news", "sql", "数据库查询出错3", 
                `select title,create_time from info_news where id=${collectionNewsIdList[i].news_id}`
            )  // [{title:"新闻标题", create_time:"xxxxxxx"}]
            collectionNewsList.push(ret[0])
        }

        console.log(collectionNewsList);
        
        
        // console.log(counts[0]["count(*)"]);
        
        let totalPage = Math.ceil(counts[0]["count(*)"]/10);

        console.log(totalPage);
        
        let data = {
            currentPage,
            totalPage,
            collectionNewsList    
        }
        res.render("news/user_collection", data)
    })();
})
module.exports = router